//
//  QSCircleProgressView.swift
//  TestSwift
//
//  Created by Song on 2019/5/16.
//  Copyright © 2019 Song. All rights reserved.
//

import UIKit

class QSCircleProgressView: UIView {
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.layer.addSublayer(bgLayer)
        self.layer.addSublayer(progressLayer)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let circlePath = UIBezierPath.init(arcCenter: CGPoint.init(x: self.bounds.width / 2.0, y: self.bounds.height / 2.0), radius: (self.bounds.width - lineWidth) / 2.0, startAngle: startAngle * CGFloat.pi / 180.0, endAngle: endAngle * CGFloat.pi / 180.0, clockwise: true)
        
        // 背景layer
        bgLayer.frame = self.bounds
        // 填充色 -  透明色
        bgLayer.fillColor = UIColor.clear.cgColor
        bgLayer.lineWidth = lineWidth
        // 线条颜色
        bgLayer.strokeColor = bgColor.cgColor
        bgLayer.strokeStart = 0.0
        bgLayer.strokeEnd = 1.0
        bgLayer.lineCap = lineCap
        bgLayer.path = circlePath.cgPath
        
        // progress layer
        progressLayer.frame = self.bounds
        progressLayer.fillColor = UIColor.clear.cgColor
        progressLayer.lineWidth = lineWidth
        progressLayer.lineCap = lineCap
        progressLayer.strokeColor = progressColor.cgColor
        progressLayer.strokeStart = 0.0
        progressLayer.strokeEnd = 0.0
        progressLayer.path = circlePath.cgPath
    }
    
    // MARK: - Property
    var bgColor: UIColor = .lightGray
    var progressColor: UIColor = .white
    var lineWidth: CGFloat = 10.0
    var lineCap: CAShapeLayerLineCap = .round
    // 水平向右为0，水平向左为180.0，垂直向下90.0，垂直向上270.0
    var startAngle: CGFloat = 0.0
    var endAngle: CGFloat = 360.0
    
    // 设置进度，有效值0~1
    func setProgress(_ progress: CGFloat, animate: Bool) {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.01) { [unowned self] in
            if animate {
                if let t = self.timer {
                    t.qs_fireTimer()
                } else {
                    self.timer = Timer.qs_init(timeInterval: 0.01, timeOut: { [weak self] (timer) in
                        if (self?.progressLayer.strokeEnd ?? 0.0) < progress {
                            self?.progressLayer.strokeEnd += 0.01
                        }
                    })
                }
            } else {
                self.progressLayer.strokeEnd = progress
            }
        }
    }
    
    private var timer: Timer?
    
    // MARK: - Widget
    private lazy var bgLayer: CAShapeLayer = {
        let layer = CAShapeLayer.init()
        return layer
    }()
    
    private lazy var progressLayer: CAShapeLayer = {
        let layer = CAShapeLayer.init()
        return layer
    }()
}
